package com.sk.waste.app.activitys

import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Button
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lc.smc.lib.annotations.LCBindView
import com.lc.smc.lib.interfaces.LCInterface
import com.lc.smc.lib.utils.LCLogger
import com.lc.smc.lib.utils.LCSPUtil
import com.sk.waste.app.R
import com.sk.waste.app.adapters.InterestAdapter
import com.sk.waste.app.adapters.TenderAdapter
import com.sk.waste.app.bases.BaseActiivity
import com.sk.waste.app.config.AppConfig
import com.sk.waste.app.config.NetWorkConfig
import com.sk.waste.app.enums.EditEmum
import com.sk.waste.app.models.TagModel
import com.sk.waste.app.utils.OkHttpUtil
import com.sk.waste.app.views.InterestDialog
import com.sk.waste.app.views.SkAlertDialog
import okhttp3.Call
import org.json.JSONObject
import java.io.IOException
import java.lang.StringBuilder
import java.util.Arrays

/**
 *  @time 2025/4/25  17:11
 *  @desc 兴趣标签
 */
class InterestActivity : BaseActiivity() {

    @LCBindView(R.id.ac_interest_add_button)
    private lateinit var bttAdd: Button

    @LCBindView(R.id.ac_interest_recyclerview)
    private lateinit var recyclerView: RecyclerView

    private lateinit var adapter: InterestAdapter
    private val list = mutableListOf<TagModel>()
    private var addDialog: InterestDialog? = null
    private var alertDialog: SkAlertDialog? = null
    private var pageState = EditEmum.ADD
    private var currentPosition = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_interest)
        super.onCreate(savedInstanceState)
        setBack()
        setTitleView("兴趣标签")
        initAdapter()
        requestList()
        bttAdd.setOnClickListener {
            pageState = EditEmum.ADD
            showAddData("")
        }
    }

    private fun initAdapter() {
        recyclerView.layoutManager = LinearLayoutManager(mContext)
        adapter = InterestAdapter(mContext, list, mOnItemClickListener)
        recyclerView.adapter = adapter
    }

    private val mOnItemClickListener = object : LCInterface.LcCallBack {
        override fun callBack(vararg args: Any?) {
            val viewId = args[0] as Int
            currentPosition = args[1] as Int
            when (viewId) {
                R.id.item_interest_look -> {
                    pageState = EditEmum.LOOK
                    val mIntent = intent
                    mIntent.putExtra("extral_str", list[currentPosition].title)
                    setResult(RESULT_OK, mIntent)
                    finish()
                }

                R.id.item_interest_edit -> {
                    pageState = EditEmum.EDIT
                    showAddData(list[currentPosition].title)
                }

                R.id.item_interest_delete -> {
                    pageState = EditEmum.DELETE
                    showAlert()
                }
            }
        }
    }

    /**
     *  @time 2025/5/9  17:53
     *  @desc 新增
     */
    private fun showAddData(content: String) {
        if (addDialog == null) {
            addDialog = InterestDialog(mContext)
            addDialog!!.setOnclickListener(mOnclickListener)
        }
        addDialog!!.setContent(content)
        addDialog!!.show()
    }

    private val mOnclickListener = object : LCInterface.LcOnPnButtonClickLitener {
        override fun onNegetiveClick(vararg args: Any?) {

        }

        override fun onPositiveClick(vararg args: Any?) {
            val lab = args[0] as String
            if (lab.isNotEmpty()) {
                if (pageState == EditEmum.EDIT) {
                    val item = list[currentPosition]
                    editIntrestTag(item.id, lab)
                } else {
                    addIntrestTag(lab)
                }
            }
        }
    }

    /**
     *  @time 2025/5/9  17:53
     *  @desc 新增
     */
    private fun showAlert() {
        if (alertDialog == null) {
            alertDialog = SkAlertDialog(mContext)
            alertDialog!!.setOnclickListener(mDeleteOnclickListener)
        }
        alertDialog!!.setTitleAndContent("删除提醒", "标签删除提醒，请确认是否要删除此条兴趣标签。")
        alertDialog!!.showExpend()
    }


    private val mDeleteOnclickListener = object : LCInterface.LcOnPnButtonClickLitener {
        override fun onNegetiveClick(vararg args: Any?) {
        }

        override fun onPositiveClick(vararg args: Any?) {
            deleteIntrestTag(list[currentPosition].id)
        }
    }

    /**
     *  @time 2025/6/6  19:41
     *  @desc 列表
     */
    private fun requestList() {
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_INTREST_LIST
        showProgress()
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequestGet(url, token, object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                cancleProgress()
                showToast("获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    cancleProgress()
                    list.clear()
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    val data = jsonObject.getJSONArray("data")
                    if (success) {
                        for (index in 0 until data.length()) {
                            val model = TagModel().apply { getModelInfo(data.getJSONObject(index)) }
                            list.add(model)
                        }
                        notifyDataSetChanged()
//                        LCLogger.d(TAG, "获取成功！,信息：$jsonObject")
                    } else {
                        showToast("获取失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    cancleProgress()
                    showToast("获取失败，" + e.message)
                }
            }
        })
    }

    /**
     *  @time 2025/6/6  19:41
     *  @desc 添加
     */
    private fun addIntrestTag(title: String) {
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_INTREST_ADD
        showProgress()
        val httpUtil = OkHttpUtil()
        val params = JSONObject()
        params.put("title", title)

        httpUtil.httpRequest(url, token, params.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                cancleProgress()
                showToast("获取失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    cancleProgress()
                    list.clear()
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    if (success) {
                        requestList()
                        showToast("操作成功！")
                        LCLogger.d(TAG, "获取成功！,信息：$jsonObject")
                    } else {
                        showToast("获取失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    cancleProgress()
                    showToast("获取失败，" + e.message)
                }
            }
        })
    }

    /**
     *  @time 2025/6/11  10:41
     *  @desc 编辑
     */
    private fun editIntrestTag(id: String, title: String) {
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_INTREST_EDIE
        showProgress()
        val httpUtil = OkHttpUtil()
        val params = JSONObject()
        params.put("id", id)
        params.put("title", title)

        httpUtil.httpRequest(url, token, params.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                cancleProgress()
                showToast("操作失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    cancleProgress()
                    list.clear()
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    if (success) {
                        requestList()
                        showToast("操作成功！")
                        LCLogger.d(TAG, "操作成功！,信息：$jsonObject")
                    } else {
                        showToast("操作失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    cancleProgress()
                    showToast("操作失败，" + e.message)
                }
            }
        })
    }

    /**
     *  @time 2025/6/11  10:41
     *  @desc 删除
     */
    private fun deleteIntrestTag(id: String) {
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_INTREST_DELETE
        showProgress()
        val httpUtil = OkHttpUtil()
        val params = JSONObject()
        params.put("id", id)

        httpUtil.httpRequest(url, token, params.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                cancleProgress()
                showToast("操作失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    cancleProgress()
                    list.clear()
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    if (success) {
                        requestList()
                        showToast("操作成功！")
                        LCLogger.d(TAG, "获取成功！,信息：$jsonObject")
                    } else {
                        showToast("操作失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    cancleProgress()
                    showToast("操作失败，" + e.message)
                }
            }
        })
    }

    private fun notifyDataSetChanged() {
        runOnUiThread { adapter.notifyDataSetChanged() }
    }

}